package com.qianyu.interceptor;


import cn.dev33.satoken.stp.StpUtil;
import com.google.common.base.Objects;
import com.qianyu.enumerate.ResultEnum;
import com.qianyu.exception.CustomerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.qianyu.enumerate.ResultEnum.USER_REQUEST_WITHOUT_TOKEN;


/**
 * @author wangzhic
 * @data 2020/8/4 13:39
 * 功能描述 状态拦截器
 * 专门用来判断用户是否登录的拦截器 类似于WEB开发中的登录过滤器的功能
 **/
public class LoginInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o){
        log.info("Token Checkout processing");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        /*从HTTP请求头中，获得令牌信息*/
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            throw new CustomerException(USER_REQUEST_WITHOUT_TOKEN);
        }
        /*验证令牌*/
        try {
            StpUtil.checkLogin();
            String tokenValue = StpUtil.getTokenValue();
            if (!Objects.equal(token, tokenValue)) {
                response.setHeader("Authorization", tokenValue);
            }
        } catch (Exception e) {
            //token不合法异常
            log.error("Token Checkout processing AlgorithmMismatchException 异常！" + e.getLocalizedMessage());
            throw new CustomerException(ResultEnum.USER_TOKEN_NOT_USE);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
